package com.example.demo.socket.channelManager;


import com.example.demo.core.exception.NotFoundException;
import com.example.demo.core.util.ThreadUtil;
import com.example.demo.socket.model.ChannelSession;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;


/**
 * @author yj
 * @date 2021/4/6 14:09
 */
public class MobileSocketManager {

    private final static Logger logger = LoggerFactory.getLogger(MobileSocketManager.class);

    private final static ConcurrentHashMap<String, ChannelSession> map;

    static {
        map = new ConcurrentHashMap<>(16);
    }

    public static void save(Channel channel, String shortId) {
        map.put(shortId, new ChannelSession(channel));
    }

    public static ChannelSession get(String shortId) {
        return map.get(shortId);
    }

    public static void remove(String shortId) {
        try {
            ChannelSession session = map.remove(shortId);
            session.close();
        } catch (NullPointerException e) {
            String methodName = ThreadUtil.getMethodName();
            logger.error("没有找到存储的信息无法操作,当前方法：{}", methodName);
        }
    }


    public static String getServerIp(String shortId) {
        try {
            ChannelSession session = get(shortId);
            return session.getServerIp();
        } catch (NullPointerException e) {
            logger.error("没有找到对应的通道Session");
            return null;
        }

    }

    public static String getClientIp(String shortId) {
        try {
            ChannelSession session = get(shortId);
            return session.getClientIp();
        } catch (NullPointerException e) {
            logger.error("没有找到对应的通道Session");
            return null;
        }
    }


    public static Boolean isActive(String shortId) {
        try {
            ChannelSession session = get(shortId);
            return session.isActive();
        } catch (NullPointerException e) {
            logger.error("没有找到对应的通道Session");
            return false;
        }

    }

    public static Boolean isWrite(String shortId) {
        try {
            ChannelSession session = get(shortId);
            return session.isWrite();
        } catch (NullPointerException e) {
            return false;
        }
    }

    public static void writeAndFlush(String shortId, String data) {
        try {
            ChannelSession session = get(shortId);
            session.writeAndFlush(data);
        } catch (NullPointerException e) {
            logger.error("没有找到对应的通道Session");
        }
    }

    public static void writeAndFlush(String shortId, byte[] data) {
        try {
            ChannelSession session = get(shortId);
            session.writeAndFlush(data);
        } catch (NullPointerException e) {
            logger.error("没有找到对应的通道Session");
        }
    }

    private static void printLog() {
        String methodName = ThreadUtil.getMethodName(-2);

    }

}